//
//  HomePageDetailViewController.m
//  miaopai
//
//  Created by Crow Zhang on 15/11/14.
//  Copyright © 2015年 Crow Zhang. All rights reserved.
//

#import "HomePageDetailViewController.h"
#import "CustomerNetworking.h"
#import "FlowWaterLayout.h"
#import "HomePageDetailCollectionViewCell.h"
#import "HomePageDetailTopic.h"
#import "Channel.h"
#import "CollectionVideoViewController.h"
#import "AutoadaptationFrame.h"
#import "TopicDetailViewController.h"
#import "VideoDetailViewController.h"
#import "SCCatWaitingHUD.h"
#import <MJRefresh.h>
#import <UINavigationBar+Awesome.h>

@interface HomePageDetailViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, FlowWaterLayoutDelegate>

@property(nonatomic, retain)UICollectionView *collectionView;

@property(nonatomic, retain)NSMutableArray *dataArray;

@property(nonatomic, assign)NSInteger loadTimes;

@end

@implementation HomePageDetailViewController

- (void)dealloc
{
    [_collectionView release];
    [_dataArray release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.loadTimes = 1;
    self.title = self.name;
    
    [self.navigationController.navigationBar setTintColor:[UIColor blackColor]];
    
    [[SCCatWaitingHUD sharedInstance] animateWithInteractionEnabled:YES];
    
    self.dataArray = [NSMutableArray array];
    [self creatCollectionView];
    [self loadData];
}

#pragma mark 解析数据
- (void)loadData
{
    NSLog(@"%@", self.scid);
    NSString *urlString;
    if (self.scid == nil) {
       urlString = [NSString stringWithFormat:@"http://api.miaopai.com/m/v5_hot_channel.json?extend=1&os=ios&page=%ld&per=20&refresh=0&unique_id=b3fff147016dcfb76717f51647daff273540160877&version=6.1.0", (long)self.loadTimes];
    }else
    {
        urlString = [NSString stringWithFormat:@"http://api.miaopai.com/m/cate2_channel?cateid=%@&extend=1&os=ios&page=%ld&per=20&type=news&unique_id=b3fff147016dcfb76717f51647daff273540160877&version=6.1.0", self.scid, (long)self.loadTimes];
    }
    
    [CustomerNetworking customerConnectWithURL:urlString andparameters:nil andBlock:^(id response) {
        [[SCCatWaitingHUD sharedInstance] stop];
        if ([[response objectForKey:@"result"] count] == 0) {
            [self.collectionView.mj_footer endRefreshingWithNoMoreData];
        }
        for (NSDictionary *dic in [response objectForKey:@"result"])
        {
            if ([[dic objectForKey:@"type"] isEqualToString:@"topic"])
            {
                HomePageDetailTopic *topic = [HomePageDetailTopic topicViewDictionary:dic];
                [self.dataArray addObject:topic];
            }else if ([[dic objectForKey:@"type"] isEqualToString:@"channel"])
            {
                Channel *channel = [Channel channelWithDic:[dic objectForKey:@"channel"]];
                [self.dataArray addObject:channel];
            }
        }
        [self.collectionView reloadData];
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshing];
    }];
}

#pragma mark 创建collectionView
- (void)creatCollectionView
{
    FlowWaterLayout *layout = [[FlowWaterLayout alloc] init];
    layout.delegate = self;
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];
    [self.collectionView setContentInset:UIEdgeInsetsMake(0, 0, -96, 0)];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor colorWithWhite:0.931 alpha:1.000];
    [self.collectionView registerClass:[HomePageDetailCollectionViewCell class] forCellWithReuseIdentifier:@"homeDeatailColllectionCell"];
    [self.view addSubview:self.collectionView];
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self.dataArray removeAllObjects];
        self.loadTimes = 1;
        [self loadData];
    }];
    self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.loadTimes++;
        [self loadData];
        NSLog(@"%ld", (long)self.loadTimes);
    }];
    [layout release];
    [_collectionView release];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

#pragma mark cell个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

#pragma mark cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    HomePageDetailCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"homeDeatailColllectionCell" forIndexPath:indexPath];
    if (_dataArray.count > 0) {
        if ([[_dataArray objectAtIndex:indexPath.item] isKindOfClass:[HomePageDetailTopic class]]) {
            HomePageDetailTopic *topic = [_dataArray objectAtIndex:indexPath.item];
            cell.topic = topic;
        }else if ([[_dataArray objectAtIndex:indexPath.item] isKindOfClass:[Channel class]])
        {
            Channel *channel = [_dataArray objectAtIndex:indexPath.item];
            cell.channel = channel;
        }
    }
   
    cell.layer.cornerRadius = 5;
    cell.layer.masksToBounds = YES;
    return cell;
}

#pragma mark flowlayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = 0;
    CGFloat width = ([UIScreen mainScreen].bounds.size.width - 30) / 2;
    if ([[_dataArray objectAtIndex:indexPath.item] isKindOfClass:[HomePageDetailTopic class]]) {
        height = -20;
    }else if ([[_dataArray objectAtIndex:indexPath.item] isKindOfClass:[Channel class]])
    {
        Channel *channel = [_dataArray objectAtIndex:indexPath.item];
        if (![channel.ext.t isEqualToString:@""]) {
            height = [AutoadaptationFrame heightOfLabel:channel.ext.t andTextFont:[UIFont systemFontOfSize:13] andLabelWidth:width - 20];
        }else
        {
            height = -20;
        }
    }
    return CGSizeMake(width, width + height + 20);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.dataArray[indexPath.item] isKindOfClass:[HomePageDetailTopic class]]) {
        if ([[self.dataArray[indexPath.item] topic] type]== TRUE) {
            CollectionVideoViewController *videoView = [[CollectionVideoViewController alloc] init];
            HomePageDetailTopic *topic = [_dataArray objectAtIndex:indexPath.item];
            NSLog(@"%@", topic.topic.stpid);
            videoView.stpid = topic.topic.stpid;
            [self.navigationController pushViewController:videoView animated:YES];
            [videoView release];
        }else
        {
            TopicDetailViewController *topicDetail = [[TopicDetailViewController alloc] init];
            [self.navigationController pushViewController:topicDetail animated:YES];
            HomePageDetailTopic *topic = [_dataArray objectAtIndex:indexPath.item];
            NSLog(@"%@", topic.topic.stpid);
            topicDetail.topicName = topic.title;
            topicDetail.stpid = topic.topic.stpid;
            UIBarButtonItem *backItem = [[UIBarButtonItem alloc] init];
            backItem.title = @"";
            self.navigationItem.backBarButtonItem = backItem;
            [backItem release];
            [topicDetail release];
        }
    }else
    {
        VideoDetailViewController *videoDetailView = [[VideoDetailViewController alloc] init];
        Channel *channel = [_dataArray objectAtIndex:indexPath.item];
        videoDetailView.scid = channel.scid;
        [self.navigationController pushViewController:videoDetailView animated:YES];
        [videoDetailView release];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat offsetY = scrollView.contentOffset.y;
    if (offsetY > 0) {
        if (offsetY >= 44) {
            [self setNavigationBarTransformProgress:1];
            //self.navigationItem.hidesBackButton = YES;
            [self.navigationController.navigationBar setTintColor:[UIColor clearColor]];
            self.title = @"";
        } else {
            [self setNavigationBarTransformProgress:(offsetY / 44)];
        }
    } else {
        [self setNavigationBarTransformProgress:0];
        self.navigationController.navigationBar.backIndicatorImage = [UIImage new];
        //self.navigationItem.hidesBackButton = NO;
        [self.navigationController.navigationBar setTintColor:[UIColor blackColor]];
        self.title = self.name;
    }
    
    //Selected index's color changed.
    static float newy = 0;
    static float oldy = 0;
    newy = scrollView.contentOffset.y ;
    if (newy != oldy ) {
        //Left-YES,Right-NO
        if (newy > oldy) {
            
        }else if(newy < oldy){
            [self setNavigationBarTransformProgress:0];
            self.navigationController.navigationBar.backIndicatorImage = [UIImage new];
            [self.navigationController.navigationBar setTintColor:[UIColor blackColor]];
            self.title = self.name;
        }
        oldy = newy;
    }
    
}

- (void)setNavigationBarTransformProgress:(CGFloat)progress
{
    [self.navigationController.navigationBar lt_setTranslationY:(-44 * progress)];
    [self.navigationController.navigationBar lt_setElementsAlpha:(1-progress)];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    UIView * view = [self.tabBarController.view.subviews lastObject];
    [UIView animateWithDuration:0.5 animations:^{
        view.frame = CGRectMake(0, kHeight + 100, kWidth, 48);
    }];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] init];
    backItem.title = @"返回";
    self.navigationItem.backBarButtonItem = backItem;
    [backItem release];
}

- (void)viewDidAppear:(BOOL)animated
{

}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar lt_reset];
}

- (void)viewDidDisappear:(BOOL)animated
{
    //self.navigationItem.hidesBackButton = NO;
    [self.navigationController.navigationBar setTintColor:[UIColor blackColor]];
    [self setNavigationBarTransformProgress:0];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
